<template>
  <div class="user-edit-container">
    <!-- Header 区域 -->
    <van-nav-bar
      title="编辑资料"
      left-arrow
      @click-left="$router.back()"
      fixed
    />

    <!-- 用户资料 -->
    <van-cell-group class="action-card">
      <van-cell title="头像" is-link center>
        <template #default>
          <van-image
            round
            class="avatar"
            :src="photo"
            @click="$refs.iptFile.click()"
          />
          <!-- file 选择框 -->
          <input
            type="file"
            ref="iptFile"
            v-show="false"
            accept="image/*"
            @change="onFileChange"
          />
        </template>
      </van-cell>
      <van-cell
        title="名称"
        is-link
        :value="userProfile.name"
        @click="changeNameFn"
      />
      <!-- 修改名称的弹出层 -->
      <van-dialog
        v-model="nameShow"
        title="修改名称"
        show-cancel-button
        :beforeClose="beforeCloseFn"
      >
        <!-- 输入框 -->
        <van-field
          :error="isErr"
          v-model.trim="userName"
          input-align="center"
          maxlength="7"
          placeholder="请输入名称"
          v-inp
        />
      </van-dialog>
      <!-- 修改生日 -->
      <van-cell
        title="生日"
        is-link
        :value="userProfile.birthday"
        @click="changeBirthdayFn"
      />
      <!-- 修改生日弹出层 -->
      <van-popup
        v-model="birthdayShow"
        round
        position="bottom"
        :style="{ height: '30%' }"
      >
        <van-datetime-picker
          v-model="userBirthday"
          type="date"
          title="选择出生日期"
          :min-date="minDate"
          :max-date="maxDate"
          :columns-order="['year', 'month', 'day']"
          :formatter="formatter"
          @confirm="confirmBir"
        />
      </van-popup>
    </van-cell-group>
  </div>
</template>

<script>
import { getUserProfile, updateImg, updataUser } from '@/api'
import { Notify, Toast } from 'vant'
import { mapMutations } from 'vuex'
export default {
  name: 'UserEdit',
  data () {
    return {
      userProfile: {
        name: '',
        birthday: ''
      },
      photo: '',
      nameShow: false,
      userName: '',
      birthdayShow: false,
      userBirthday: new Date(),
      minDate: new Date('1900-01-01'),
      maxDate: new Date(),
      isErr: false
    }
  },
  created () {
    this.getUserProfileFn()
  },
  methods: {
    ...mapMutations('user', ['setheadImgMutations', 'setuserNameMutations']),
    async getUserProfileFn () {
      const res = await getUserProfile()
      this.userProfile.name = res.data.data.name
      this.userProfile.birthday = res.data.data.birthday
      this.photo = res.data.data.photo
      this.userBirthday = new Date(this.userProfile.birthday)
    },
    async onFileChange (e) {
      if (e.target.files.length === 0) return
      // 实例化一个formDate对象
      const fd = new FormData()
      // 添加一个新值到 FormData 对象内
      fd.append('photo', e.target.files[0])
      const res = await updateImg(fd)
      this.setheadImgMutations(res.data.data.photo)
      this.getUserProfileFn()
    },
    changeNameFn () {
      this.nameShow = true
      this.userName = this.userProfile.name
    },

    // 弹框关闭前的回调函数
    // action:表示点击那个按钮，cancel表示点击取消/confirm表示点击确认
    async beforeCloseFn (action, done) {
      if (action === 'confirm') {
        // 如果没有填点击确认
        if (/^[A-Za-z0-9\u4e00-\u9fa5]{1,7}$/.test(this.userName)) {
          const data = {
            name: this.userName
          }
          await updataUser(data)
          this.setuserNameMutations(this.userName)

          this.getUserProfileFn()

          Toast.success('修改用户名成功')
          this.userName = ''
          done()
        } else {
          // 提示用户
          Notify({ type: 'warning', message: '用户名中英文和数字1-7位' })
          // 阻止弹窗关闭
          done(false)
        }
      } else if (action === 'cancel') {
        done()
      }
    },
    // 控制日期选择器显隐
    changeBirthdayFn () {
      this.birthdayShow = true
    },
    // 日期格式化
    formatter (type, val) {
      if (type === 'year') {
        return val + '年'
      }
      if (type === 'month') {
        return val + '月'
      }
      if (type === 'day') {
        return val + '日'
      }
      return val
    },
    async confirmBir () {
      const birthday = this.$moment(this.userBirthday).format('YYYY-MM-DD')
      const data = {
        birthday: birthday
      }
      await updataUser(data)
      this.getUserProfileFn()
      Toast.success('修改生日成功')
      this.birthdayShow = false
    }
  }
}
</script>

<style lang="less" scoped>
.user-edit-container {
  padding-top: 46px;
  .avatar {
    width: 50px;
    height: 50px;
  }
}
.van-nav-bar {
  background: #007bff;
}

//::v-deep 就是把data-v-hash值选择器写到类名的前面
::v-deep .van-nav-bar__title {
  color: #fff;
}
/deep/.van-icon {
  color: #fff;
}
.van-cell__right-icon {
  color: #969799;
}
</style>
